package com.zhuchaooasystem.ui.home.fragment.oa.record;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.zhuchaooasystem.R;
import com.zhuchaooasystem.adapter.MyPageAdapter;
import com.zhuchaooasystem.adapter.holder.RecordListHolder;
import com.zhuchaooasystem.adapter.holder.RecordUploadHolder;
import com.zhuchaooasystem.base.BaseActivity;
import com.zhuchaooasystem.base.BaseEvent;
import com.zhuchaooasystem.common.Key;
import com.zhuchaooasystem.entity.AudioInfo;
import com.zhuchaooasystem.entity.RecordEntity;
import com.zhuchaooasystem.entity.UserInfo;
import com.zhuchaooasystem.presenter.home.fragment.oa.record.RecordContract;
import com.zhuchaooasystem.presenter.home.fragment.oa.record.RecordPresenter;
import com.zhuchaooasystem.utils.AppUtils;
import com.zhuchaooasystem.utils.CalendarUtils;
import com.zhuchaooasystem.utils.ListUtils;
import com.zhuchaooasystem.utils.NetWorkUtil;
import com.zhuchaooasystem.utils.ToastUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.zhuchaooasystem.utils.ListUtils.listPlus;

public class RecordActivity extends BaseActivity<RecordPresenter> implements RecordContract.View, RecyclerArrayAdapter.OnMoreListener, SwipeRefreshLayout.OnRefreshListener {

    public static final int UPLOAD_RECORD_MAX = 5;

    @BindView(R.id.actionbar_iv_back)
    ImageView iv_back;
    @BindView(R.id.actionbar_txt_title)
    TextView txt_title;
    @BindView(R.id.actionbar_txt_right)
    TextView txt_right;
    @BindView(R.id.act_record_vp_records)
    ViewPager vp_records;
    @BindView(R.id.act_record_iv_take_record)
    ImageView iv_take_record;
    @BindView(R.id.act_record_tv_take_record)
    TextView tv_take_record;
    @BindView(R.id.act_record_iv_record_list)
    ImageView iv_record_list;
    @BindView(R.id.act_record_tv_record_list)
    TextView tv_record_list;
    //----
    private UserInfo userInfo;
    //----
    private List<View> viewList;
    //----录音相关
    private View view_record;
    private TextView tv_name;
    private TextView tv_cur_date;
    private EditText et_topic;
    private EditText et_remark;
    private TextView tv_upload_notice;
    private ImageView iv_to_take_record;
    private ImageView iv_to_local_record;
    private EasyRecyclerView recycle_record;
    private List<AudioInfo> audioInfoList;
    private RecyclerArrayAdapter uploadRecordAdapter;
    private MediaPlayer mediaPlayer;
    //----录音列表相关
    private View view_record_list;
    private int index;
    private List<RecordEntity.ResultBean.SuccessfulBean> recordList;
    private EasyRecyclerView recycle_list;
    private RecyclerArrayAdapter recordListAdapter;
    //----
    private int cur_position; //当前播放录音文件的index,值为0表示没有播放
    private boolean showDelete;

    @Override
    protected int getLayout() {
        return R.layout.activity_record;
    }

    @Override
    protected RecordPresenter getPresenter() {
        return new RecordPresenter(mContext, this);
    }

    @Override
    protected void initVariables() {
        userInfo = UserInfo.getInstance();
        mediaPlayer = new MediaPlayer();
        audioInfoList = new ArrayList<>();
        index = 1;
        cur_position = -1;
        RxBus.get().register(this);
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag("takeRecord")})
    public void takeRecord(BaseEvent baseEvent) {
        if (null != baseEvent && null!=baseEvent.event) {
            List<AudioInfo> audioInfoListTemp = (List<AudioInfo>) baseEvent.event;
            audioInfoList = ListUtils.listPlus(audioInfoList, audioInfoListTemp);
            uploadRecordAdapter.clear();
            uploadRecordAdapter.addAll(audioInfoList);
        }
    }
    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag("localRecord")})
    public void localRecord(BaseEvent baseEvent) {
        if (null != baseEvent && null!=baseEvent.event) {
            if (null != audioInfoList && audioInfoList.size() > 0) {
                audioInfoList.clear();
            }
            List<AudioInfo> audioInfoListTemp= (List<AudioInfo>) baseEvent.event;
            audioInfoList.addAll(audioInfoListTemp);
            uploadRecordAdapter.clear();
            uploadRecordAdapter.addAll(audioInfoList);
        }
    }

    @Override
    protected void initView() {
        setActionBar();
        //----
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                cur_position = -1;
                uploadRecordAdapter.notifyDataSetChanged();
            }
        });
        //----
        initViewPager();
    }

    private void setActionBar() {
        txt_title.setText(getString(R.string.actionbar_title_record));
        txt_right.setText("保存");
        txt_right.setClickable(true);
        txt_right.setVisibility(View.VISIBLE);
        iv_back.setVisibility(View.VISIBLE);
    }

    private void initViewPager() {
        viewList = new ArrayList<>();
        view_record = LayoutInflater.from(mContext).inflate(R.layout.activity_record_vp_record, null);
        view_record_list = LayoutInflater.from(mContext).inflate(R.layout.activity_record_vp_record_list, null);
        viewList.add(view_record);
        viewList.add(view_record_list);
        //----
        initViewRecord();
        initViewRecordList();
        //----
        vp_records.setAdapter(new MyPageAdapter(viewList));
        vp_records.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                mPresenter.pagerChanged(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 初始化录音界面
     */
    private void initViewRecord() {
        findViewByIdRecord();
        //----
        tv_name.setText(userInfo.getUserName());
        tv_cur_date.setText("当前日期：" + CalendarUtils.getNow("yyyy-MM-dd HH:mm:ss"));
        iv_to_take_record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                turnToTakeRecord();
            }

            private void turnToTakeRecord() {
                if (null != audioInfoList && audioInfoList.size() == 5) {
                    ToastUtil.showShort(mContext, "最多上传" + UPLOAD_RECORD_MAX + "个录音文件");
                    return;
                }
                recover();
                AppUtils.jump(mContext, TakeRecordActivity.class);
            }
        });
        iv_to_local_record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                turnToLocalRecord();
            }

            private void turnToLocalRecord() {
                recover();
                //----
                ArrayList<String> audioList = new ArrayList<>();
                for (int i = 0; i < audioInfoList.size(); i++) {
                    audioList.add(audioInfoList.get(i).getFilePath());
                }
                Bundle bundle = new Bundle();
                bundle.putStringArrayList("audioList", audioList);
                AppUtils.jump(mContext, LocalRecordActivity.class, bundle);
            }
        });
        //----
        initRecycleRecord();
    }

    private void initRecycleRecord() {
        //----
        recycle_record.setLayoutManager(new LinearLayoutManager(mContext));
        recycle_record.setAdapterWithProgress(uploadRecordAdapter = new RecyclerArrayAdapter<AudioInfo>(mContext) {

            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new RecordUploadHolder(parent, RecordActivity.this);
            }
        });
    }

    private void findViewByIdRecord() {
        tv_name = (TextView) view_record.findViewById(R.id.act_record_vp_record_tv_name);
        tv_cur_date = (TextView) view_record.findViewById(R.id.act_record_vp_record_tv_date);
        et_topic = (EditText) view_record.findViewById(R.id.act_record_vp_record_edit_topic);
        et_remark = (EditText) view_record.findViewById(R.id.act_record_vp_record_edit_remark);
        tv_upload_notice = (TextView) view_record.findViewById(R.id.act_record_vp_record_tv_upload);
        iv_to_take_record = (ImageView) view_record.findViewById(R.id.act_record_vp_record_iv_take);
        iv_to_local_record = (ImageView) view_record.findViewById(R.id.act_record_vp_record_iv_local);
        recycle_record = (EasyRecyclerView) view_record.findViewById(R.id.act_record_vp_record_recycle_upload);
    }

    private void recover() {
        if (showDelete) {
            showDelete = false;
        }
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        cur_position = -1;
        uploadRecordAdapter.notifyDataSetChanged();
    }

    /**
     * 初始化录音列表界面
     */
    private void initViewRecordList() {
        recycle_list = (EasyRecyclerView) view_record_list.findViewById(R.id.act_record_vp_record_list_recycle);
        recycle_list.setRefreshingColor(Key.RECYCLEVIEW_REFRESH_COLORS);
        recycle_list.setLayoutManager(new LinearLayoutManager(mContext));
        recycle_list.setAdapterWithProgress(recordListAdapter = new RecyclerArrayAdapter<RecordEntity.ResultBean.SuccessfulBean>(mContext) {

            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new RecordListHolder(parent);
            }
        });
        recycle_list.setEmptyView(R.layout.view_empty);
        //----
        recycle_list.setRefreshListener(this);
        recordListAdapter.setMore(R.layout.view_more, this);
        recordListAdapter.setNoMore(R.layout.view_nomore, new RecyclerArrayAdapter.OnNoMoreListener() {
            @Override
            public void onNoMoreShow() {
                recordListAdapter.resumeMore();
            }

            @Override
            public void onNoMoreClick() {
                recordListAdapter.resumeMore();
            }
        });
        recordListAdapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                recordListAdapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                recordListAdapter.resumeMore();
            }
        });
        recordListAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                }
                cur_position = -1;
                uploadRecordAdapter.notifyDataSetChanged();
                Bundle bundle = new Bundle();
                bundle.putParcelable("record", recordList.get(position));
                AppUtils.jump(mContext, RecordDetailActivity.class, bundle);
            }
        });

    }


    @Override
    protected void initDataAndLoadData() {
        //----
        onRefresh();
    }

    @Override
    public void setCurrentItem(int position) {
        vp_records.setCurrentItem(position);
        if (position == 0) {
            txt_right.setVisibility(View.VISIBLE);
        } else {
            txt_right.setVisibility(View.GONE);
        }
    }

    @Override
    public void radioGroupChanged(int position) {
        if (position == 0) {
            iv_take_record.setBackgroundResource(R.drawable.ic_record_yes);
            tv_take_record.setTextColor(getResources().getColor(R.color.color_7f7f7f));
            iv_record_list.setBackgroundResource(R.drawable.ic_record_list_no);
            tv_record_list.setTextColor(getResources().getColor(R.color.color_1bc3ad));
        } else if (position == 1) {
            iv_take_record.setBackgroundResource(R.drawable.ic_record_no);
            tv_take_record.setTextColor(getResources().getColor(R.color.color_1bc3ad));
            iv_record_list.setBackgroundResource(R.drawable.ic_record_list_yes);
            tv_record_list.setTextColor(getResources().getColor(R.color.color_7f7f7f));
        }
    }

    @Override
    public void refreshData(List<RecordEntity.ResultBean.SuccessfulBean> data) {
        this.recordList = data;
        recordListAdapter.clear();
        recordListAdapter.addAll(data);
    }

    @Override
    public void loadMoreData(List<RecordEntity.ResultBean.SuccessfulBean> data) {
        this.recordList = listPlus(recordList, data);
        recordListAdapter.addAll(data);
    }

    @Override
    public void onClickDelete(int position) {
        if (txt_right.isClickable()) {
            if (mediaPlayer.isPlaying()) {
                cur_position = -1;
                mediaPlayer.stop();
            }
            audioInfoList.remove(position);
            uploadRecordAdapter.clear();
            uploadRecordAdapter.addAll(audioInfoList);
        }
    }

    @Override
    public void onLongClick(int position) {
        if (txt_right.isClickable()) {
            showDelete = true;
            uploadRecordAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onClickPlay(int position) {
        try {
            if (txt_right.isClickable()) {
                if (cur_position == position) {
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.stop();
                        cur_position = -1;
                        uploadRecordAdapter.notifyDataSetChanged();
                    } else {
                        cur_position = position;
                        uploadRecordAdapter.notifyDataSetChanged();
                        mediaPlayer.reset();
                        mediaPlayer.setDataSource(audioInfoList.get(position).getFilePath());
                        mediaPlayer.prepare();
                        mediaPlayer.start();
                    }
                } else {
                    cur_position = position;
                    uploadRecordAdapter.notifyDataSetChanged();
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.stop();
                    }
                    mediaPlayer.reset();
                    mediaPlayer.setDataSource(audioInfoList.get(position).getFilePath());
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                }
            }
        } catch (IOException e) {
            ToastUtil.showShort(mContext, "该文件无法播放");
            cur_position = -1;
            uploadRecordAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public String getThemeContent() {
        return et_topic.getText().toString();
    }

    @Override
    public String getRemark() {
        return et_remark.getText().toString();
    }

    @Override
    public void setClickable(boolean clickable) {
        txt_right.setClickable(clickable);
    }

    @Override
    public List<AudioInfo> getAudioInfoList() {
        return audioInfoList;
    }

    @Override
    public void changeView() {
        tv_upload_notice.setVisibility(View.GONE);
        et_topic.setEnabled(true);
        et_remark.setEnabled(true);
        txt_right.setClickable(true);
        iv_to_take_record.setClickable(true);
        iv_to_local_record.setClickable(true);
    }

    @Override
    public void uploadSuccuss() {
        ToastUtil.showShort(mContext, "保存成功");
        changeView();
        et_topic.setText("");
        et_remark.setText("");
        if (null != audioInfoList && audioInfoList.size() > 0) {
            audioInfoList.clear();
            uploadRecordAdapter.clear();
            uploadRecordAdapter.notifyDataSetChanged();
        }
        radioGroupChanged(1);
        onRefresh();
    }

    @OnClick({R.id.actionbar_iv_back, R.id.actionbar_txt_right, R.id.act_record_linear_records, R.id.act_record_linear_record_list})
    public void onClick(View view) {
        switch (view.getId()) {
            //返回
            case R.id.actionbar_iv_back:
                finish();
                break;
            //上传
            case R.id.actionbar_txt_right:
                if (TextUtils.isEmpty(et_topic.getText().toString())) {
                    ToastUtil.showShort(mContext, "请输入录音主题");
                    return;
                }
                if (null != audioInfoList && audioInfoList.size() > 0) {
                    int fileSize = 0;
                    for (int i = 0; i < audioInfoList.size(); i++) {
                        File file = new File(audioInfoList.get(i).getFilePath());
                        fileSize += file.length();
                        if (fileSize > 50 * 1024 * 1024) {
                            ToastUtil.showShort(mContext, "上传文件的总大小不允许超过50M");
                            return;
                        }
                    }
                    txt_right.setClickable(false);
                    et_topic.setEnabled(false);
                    et_remark.setEnabled(false);
                    iv_to_take_record.setClickable(false);
                    iv_to_local_record.setClickable(false);
                    tv_upload_notice.setVisibility(View.VISIBLE);
                    if (showDelete) {
                        showDelete = false;
                        uploadRecordAdapter.notifyDataSetChanged();
                    }
                    mPresenter.upload();
                } else {
                    ToastUtil.showShort(mContext, "请至少选择一个录音文件");
                    return;
                }
                break;
            //录音
            case R.id.act_record_linear_records:
                mPresenter.pagerChanged(0);
                break;
            //录音记录
            case R.id.act_record_linear_record_list:
                mPresenter.pagerChanged(1);
                break;
        }
    }

    @Override
    public void onRefresh() {
        //刷新
        if (!NetWorkUtil.isNetConnected(mContext)) {
            recordListAdapter.pauseMore();
            return;
        }
        index = 1;
        mPresenter.getRecordList(index);
    }

    @Override
    public void onMoreShow() {
        index++;
        mPresenter.getRecordList(index);
    }

    @Override
    public void onMoreClick() {
        mPresenter.getRecordList(index);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(this);
        if (null != mediaPlayer) {
            mediaPlayer.stop();
            //释放资源
            mediaPlayer.release();
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == MotionEvent.ACTION_UP) {
            if (vp_records.getCurrentItem() == 0) {
                if (showDelete) {
                    setShowDelete(false);
                    uploadRecordAdapter.notifyDataSetChanged();
                    return false;
                }
            }
        }
        return super.dispatchKeyEvent(event);
    }

    public int getCur_position() {
        return cur_position;
    }

    public void setCur_position(int cur_position) {
        this.cur_position = cur_position;
    }

    public boolean isShowDelete() {
        return showDelete;
    }

    public void setShowDelete(boolean showDelete) {
        this.showDelete = showDelete;
    }
}
